//
//  AppDelegate.m
//  x2
//
//  Created by wuzhx on 16/6/24.
//  Copyright © 2016年 onestep. All rights reserved.
//

#import "AppDelegate.h"
#import <xtest/CAPlatform.h>
#import <YunCeng/YunCeng.h>
#import <CAWXYUpload/TXYBase.h>
#import <CAWXYUpload/TXYUploadManager.h>
#import <Bugly/Bugly.h>


#define BUGLY_APP_ID @"900045016"

static NSUncaughtExceptionHandler *handler;

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    CAPlatformInitConfig *config = [[CAPlatformInitConfig alloc] init];
    config.umengAppKey     = @"56727313e0f55ad39400034a";
    
    config.weiBoAppKey     = @"3258263226";
    config.weiBoAppSecret  = @"4375d80891558f427ce619a29e9436e5";
    config.weiBoAppUrl     = @"http://sns.whalecloud.com/sina2/callback";
    
    config.weiXinAppKey    = @"wx7eaad1a7197d5a01";
    config.weiXinAppSecret = @"f3077878856a7ba4ecc9effbfcc45eaa";
    config.weiXinAppUrl    = @"http://www.feiyu.com";
    
    config.qqAppKey        = @"1104663351";
    config.qqAppSecret     = @"hyd9Iv81vGDoBJeY";
    config.qqAppUrl        = @"http://www.feiyu.com";
    
    config.fbAppKey        = @"154906978258974";
    config.fbAppUrl        = @"http://www.feiyu.com";
    
    config.useNotification = YES;
    config.launchOptions = launchOptions;
    config.isProduction = NO;
    config.useEmbeddedUI = YES;
    config.isSupportChallenge = YES;
    config.isDebug = NO;
    
    // 内网11111
    //    [config setValue:@"1" forKey:@"Intranet"];
    //    [[CAPlatform sharedInstance]initialize:config GameID:1 secret:@"IqrB5KSBiDHGqlEf9CNwNlbUHCzj3jXX" ChannelID:@"100000"];
    // 外网11111
    [[CAPlatform sharedInstance]initialize:config GameID:1 secret:@"skInE8BLnv35mMKtKeg6ZVT4SOf6SbSl" ChannelID:@"100000"];
    
    
    handler = NSGetUncaughtExceptionHandler();
    NSLog(@"hander = %p", handler);
    if (handler) {
        NSLog(@"hander");
    }else {
        NSLog(@"nil");
    }
    
    // 捕获异常
    NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler1);
    
    // Init the Bugly sdk
    [self setupBugly];
    
    return YES;
}


- (void)setupBugly {
    // Get the default config
    BuglyConfig * config = [[BuglyConfig alloc] init];
    
    // Open the debug mode to print the sdk log message.
    // Default value is NO, please DISABLE it in your RELEASE version.
#if DEBUG
    config.debugMode = YES;
#endif
    
    // Open the customized log record and report, BuglyLogLevelWarn will report Warn, Error log message.
    // Default value is BuglyLogLevelSilent that means DISABLE it.
    // You could change the value according to you need.
    config.reportLogLevel = BuglyLogLevelWarn;
    
    // Open the STUCK scene data in MAIN thread record and report.
    // Default value is NO
    config.blockMonitorEnable = YES;
    
    // Set the STUCK THRESHOLD time, when STUCK time > THRESHOLD it will record an event and report data when the app launched next time.
    // Default value is 3.5 second.
    config.blockMonitorTimeout = 1.5;
    
    // Set the app channel to deployment
    config.channel = @"Bugly";
    
    // NOTE:Required
    // Start the Bugly sdk with APP_ID and your config
    [Bugly startWithAppId:BUGLY_APP_ID
#if DEBUG
        developmentDevice:YES
#endif
                   config:config];
    
    // Set the customizd tag thats config in your APP registerd on the  bugly.qq.com
    //    [Bugly setTag:1799];
    
    [Bugly setUserIdentifier:[NSString stringWithFormat:@"User: %@", [UIDevice currentDevice].name]];
    
    [Bugly setUserValue:[NSProcessInfo processInfo].processName forKey:@"App"];
    
    // NOTE: This is only TEST code for BuglyLog , please UNCOMMENT it in your code.
    [self performSelectorInBackground:@selector(testLogOnBackground) withObject:nil];
}

/**
 *    @brief TEST method for BuglyLog
 */
- (void)testLogOnBackground {
    int cnt = 0;
    while (1) {
        cnt++;
        
        switch (cnt % 5) {
            case 0:
                BLYLogError(@"Test Log Print %d", cnt);
                break;
            case 4:
                BLYLogWarn(@"Test Log Print %d", cnt);
                break;
            case 3:
                BLYLogInfo(@"Test Log Print %d", cnt);
                BLYLogv(BuglyLogLevelWarn, @"BLLogv: Test", NULL);
                break;
            case 2:
                BLYLogDebug(@"Test Log Print %d", cnt);
                BLYLog(BuglyLogLevelError, @"BLLog : %@", @"Test BLLog");
                break;
            case 1:
            default:
                BLYLogVerbose(@"Test Log Print %d", cnt);
                break;
        }
        
        // print log interval 1 sec.
        sleep(1);
    }
}

//void my_NSSetUncaughtExceptionHandler( NSUncaughtExceptionHandler * handler)
//{
//    g_vaildUncaughtExceptionHandler = NSGetUncaughtExceptionHandler();
//    if (g_vaildUncaughtExceptionHandler != NULL) {
//        NSLog(@"UncaughtExceptionHandler=%p",g_vaildUncaughtExceptionHandler);
//    }
//    
//    ori_NSSetUncaughtExceptionHandler(handler);
//    NSLog(@"%@",[NSThread callStackSymbols]);
//    
//    g_vaildUncaughtExceptionHandler = NSGetUncaughtExceptionHandler();
//    NSLog(@"UncaughtExceptionHandler=%p",g_vaildUncaughtExceptionHandler);
//}

#pragma mark - 初始化配置友盟平台相关信息
void UncaughtExceptionHandler1(NSException *exception) {
    NSLog(@"hehehe....");
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    NSArray *arraddr = [exception callStackReturnAddresses];//堆栈地址
    NSString *reason = [exception reason];//非常重要，就是崩溃的原因
    NSString *name = [exception name];//异常类型
    UIDevice *device = [UIDevice currentDevice];
    
    NSDate *currentTime = [NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale currentLocale]];
    formatter.timeStyle = NSDateFormatterShortStyle;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:currentTime];
    
    NSString *strErr = [NSString stringWithFormat:@"\n device : %@ \n system : %@ \n game : %d \n sdk : %@ \n time : %@ \n exception type : %@ \n crash reason : %@ \n call stack info : %@\ncall stack addr : %@", device.model, device.systemVersion, 0, nil, dateString, name, reason, arr, arraddr];
    NSLog(@"%@", strErr);
    
    NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
    [storage setValue:strErr forKey:@"crash_log"];
    [storage synchronize];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    strErr = [NSString stringWithFormat:@"it's me la. \n %@", strErr];
    pasteboard.string = strErr;
    
    if (handler) {
        handler(exception);
    }
}

#pragma mark - urlscheme
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [[CAPlatform sharedInstance]handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    return  [[CAPlatform sharedInstance]handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return  [[CAPlatform sharedInstance]handleOpenURL:url];
}

#pragma mark - 推送 begin
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [CAPlatform registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [CAPlatform didReceiveRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [CAPlatform didReceiveLocalNotification:notification];
}

// ios9
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)())completionHandler
{
    [CAPlatform didReceiveRemoteNotification:userInfo handleActionIdentifier:identifier responseInfo:responseInfo];
    completionHandler();
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)())completionHandler
{
    [CAPlatform didReceiveLocalNotification:notification handleActionIdentifier:identifier responseInfo:responseInfo];
    completionHandler();
}

// ios8
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
    [CAPlatform didReceiveRemoteNotification:userInfo handleActionIdentifier:identifier];
    completionHandler();
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler
{
    [CAPlatform didReceiveLocalNotification:notification handleActionIdentifier:identifier];
    completionHandler();
}
#pragma mark 推送 end
#pragma mark -


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
